<?php

namespace app\api\model;

use think\Model;
use think\Session;
use app\common\traits\model\TraitModel;

class Users extends Model
{
    use TraitModel;
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $table = 'users';
    protected $error = '';
    //protected static $loginuser = '';

    public function addUser($user_info = [])
    {
        if (true == !$this->checkUser($user_info, ['mobile'])) {
            $user_info['password'] = md5($user_info['password']);
            return self::create($user_info);
        }else {
            return false;
        }   
    }
    /**
     * 校验用户信息是否存在
     * @param  [type] $user_info [description]
     * @param  array  $onlys     [description]
     * @return [type]            [description]
     */
    public function checkUser($user_info, $onlys = [])
    {
        $user_info = $onlys ? array_intersect_key($user_info, array_flip($onlys)) : $user_info;
        if (!empty($user_info)) {
            foreach ($user_info as $key => $data) {
                if (self::getUserInfo([$key => $data])) {
                    $this->error = lang($key);
                    return true;
                }
            }
        }       
        return false;
    }
    /**
     * [getUserInfo description]
     * @param  array  $where [description]
     * @param  string $field [description]
     * @return [type]        [description]
     */
    public static function getUserInfo($where = [], $field = '')
    {
        if (empty($where)) {
            return false;
        }
        if ($userInfo = self::get($where)) {
            if ($field) {
                if (isset($userInfo->$field)) {
                    return $userInfo->$field; 
                }
                return false;
            }
            return $userInfo;
        }
        return false;        
        
    }
    /**
     * 登录
     * @param  [type] $account     [description]
     * @param  [type] $password    [description]
     * @return [type]              [description]
     */
    public function login($account, $password)
    {
        if ($userInfo = self::getUserInfo(['mobile' => $account])) {
            if (md5($password) === $userInfo['password']) {
                return $userInfo;
            }
        }
        return false;
    }
    public function getError()
    {
        return $this->error;
    }
}
